package com.linkage.seapeak.utils;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.target.Target;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class FileUtils {

    public static String DIR_IMAGE = "saveImage";
    public static String DIR_FILE  = "saveFile";
    public static String DIR_TEMP  = "temp";

    public static File createFile( String path, String fileName ) {
        try {
            // 保存裁剪后的图片文件
            File pictureFileDir = new File(path);
            if (!pictureFileDir.exists()) {
                pictureFileDir.mkdirs();
            }
            File picFile = new File(pictureFileDir, fileName);
            if (!picFile.exists()) {
                picFile.createNewFile();
            }

            return picFile;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static File DeleteFile( String path, String fileName ) {
        try {
            // 保存裁剪后的图片文件
            File pictureFileDir = new File(path);
            if (!pictureFileDir.exists()) {
                pictureFileDir.mkdirs();
            }
            File picFile = new File(pictureFileDir, fileName);
            if (!picFile.exists()) {
                picFile.delete();
            }

            return picFile;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String getSD() {
        String filepath = Environment.getExternalStorageDirectory()
                .getAbsolutePath();
        return filepath;
    }

    /**
     * 获取APP维护的地址
     *
     * @return
     */
    public static String getAppPath() {
        String filepath = getSD() + File.separator + "PoXiao" + File.separator;
        return filepath;
    }

    /**
     * 保存网络文件到本地
     *
     * @param context
     * @param url
     */
    public static void saveNetFileToSD( final Context context, final String url, final String fname ) {
        new AsyncTask<Void, Void, Integer>() {

            File imageFile;

            @Override
            protected Integer doInBackground( Void... voids ) {
                try {
                    // 首先保存图片
                    final File appDir = new File(getAppPath(), DIR_FILE);
                    if (!appDir.exists()) {
                        appDir.mkdir();
                    }
                    final String fileName = System.currentTimeMillis() + fname;
                    imageFile = createFile(appDir.getAbsolutePath(), fileName);

                    FutureTarget<File> future   = Glide.with(context).load(url).downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
                    File               tempFile = future.get();
                    copyFile(tempFile, imageFile);

                    Log.i("Glide", "==Download onResourceReady: " + tempFile.getAbsolutePath());
                    //                    // 其次把文件插入到系统图库
                    //                    try {
                    //                        MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    //                                imageFile.getAbsolutePath(), fileName, "download from poxiao");
                    //                    } catch (FileNotFoundException e) {
                    //                        e.printStackTrace();
                    //                    }
                    // 最后通知图库更新
                    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                                     Uri.parse("file://" + imageFile.getAbsolutePath())));
                    return 0;
                } catch (Exception e) {
                    e.printStackTrace();
                    return -1;
                }
            }

            @Override
            protected void onPostExecute( Integer integer ) {
                super.onPostExecute(integer);
                if (integer == 0)
                    ToastUtil.getInstance((Activity) context).showLongToast("文件保存成功\n" + imageFile.getAbsolutePath(), ToastUtil.TOAST_TYPE.SUCCESS);
                else
                    ToastUtil.getInstance((Activity) context).showToast("文件保存失败", ToastUtil.TOAST_TYPE.ERROR);
            }
        }.execute();
    }


    /**
     * 保存网络图片到相册
     *
     * @param context
     * @param imageUrl
     */
    public static void saveNetImageToGallery( final Context context, final String imageUrl ) {
        new AsyncTask<Void, Void, Integer>() {

            File imageFile;

            @Override
            protected Integer doInBackground( Void... voids ) {
                try {
                    // 首先保存图片
                    final File appDir = new File(getAppPath(), DIR_IMAGE);
                    if (!appDir.exists()) {
                        appDir.mkdir();
                    }
                    final String fileName = System.currentTimeMillis() + ".jpg";
                    imageFile = createFile(appDir.getAbsolutePath(), fileName);

                    FutureTarget<File> future   = Glide.with(context).load(imageUrl).downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
                    File               tempFile = future.get();
                    copyFile(tempFile, imageFile);

                    Log.i("Glide", "==Download onResourceReady: " + tempFile.getAbsolutePath());
                    // 其次把文件插入到系统图库
                    try {
//                        MediaStore.Images.Media.insertImage(context.getContentResolver(),
//                                                            imageFile.getAbsolutePath(), fileName, "download from poxiao");
                        ContentValues values = new ContentValues();
                        values.put(MediaStore.Images.Media.DATA, imageFile.getAbsolutePath());
                        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                        Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + imageFile.getAbsolutePath())));


                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    DeleteFile(tempFile.getPath(),tempFile.getName());
                    // 最后通知图库更新
//                    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
//                                                     Uri.parse("file://" + imageFile.getAbsolutePath())));
                    return 0;
                } catch (Exception e) {
                    e.printStackTrace();
                    return -1;
                }
            }

            @Override
            protected void onPostExecute( Integer integer ) {
                super.onPostExecute(integer);
                if (integer == 0)
                    ToastUtil.getInstance((Activity) context).showLongToast("图片保存成功\n" + imageFile.getAbsolutePath(), ToastUtil.TOAST_TYPE.SUCCESS);
                else
                    ToastUtil.getInstance((Activity) context).showToast("图片保存失败", ToastUtil.TOAST_TYPE.ERROR);
            }
        }.execute();
    }

    /**
     * 复制图片到相册
     *
     * @param context
     * @param imagePath
     */
    public static void copyImageToGallery( final Context context, final String imagePath ) {
        new AsyncTask<Void, Void, Integer>() {

            File imageFile;

            @Override
            protected Integer doInBackground( Void... voids ) {
                try {
                    // 首先保存图片
                    final File appDir = new File(getAppPath(), DIR_IMAGE);
                    if (!appDir.exists()) {
                        appDir.mkdir();
                    }
                    final String fileName = System.currentTimeMillis() + ".jpg";
                    imageFile = createFile(appDir.getAbsolutePath(), fileName);

                    File tempFile = new File(imagePath);
                    copyFile(tempFile, imageFile);

                    Log.i("Glide", "==Download onResourceReady: " + tempFile.getAbsolutePath());
                    // 其次把文件插入到系统图库
                    try {
                        MediaStore.Images.Media.insertImage(context.getContentResolver(),
                                                            imageFile.getAbsolutePath(), fileName, "download from poxiao");
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    // 最后通知图库更新
                    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                                     Uri.parse("file://" + imageFile.getAbsolutePath())));
                    return 0;
                } catch (Exception e) {
                    e.printStackTrace();
                    return -1;
                }
            }

            @Override
            protected void onPostExecute( Integer integer ) {
                super.onPostExecute(integer);
                if (integer == 0)
                    ToastUtil.getInstance((Activity) context).showToast("图片保存成功\n" + imageFile.getAbsolutePath(), ToastUtil.TOAST_TYPE.SUCCESS);
                else
                    ToastUtil.getInstance((Activity) context).showToast("图片保存失败", ToastUtil.TOAST_TYPE.ERROR);
            }
        }.execute();
    }

    /**
     * 保存图片获取路径
     *
     * @param bmp
     */
    public static File saveBitmapToTempFile( Bitmap bmp ) throws IOException {
        // 首先保存图片
        File appDir = new File(getAppPath(), DIR_TEMP);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String           fileName = System.currentTimeMillis() + ".jpg";
        File             file     = createFile(appDir.getAbsolutePath(), fileName);
        FileOutputStream fos      = new FileOutputStream(file);
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
        return file;
    }


    public static boolean copyFile( File s, File t ) {
        boolean          copy = true;
        FileInputStream  fi   = null;
        FileOutputStream fo   = null;
        FileChannel      in   = null;
        FileChannel      out  = null;
        try {
            fi = new FileInputStream(s);
            fo = new FileOutputStream(t);
            in = fi.getChannel();//得到对应的文件通道
            out = fo.getChannel();//得到对应的文件通道
            in.transferTo(0, in.size(), out);//连接两个通道，并且从in通道读取，然后写入out通道
        } catch (IOException e) {
            e.printStackTrace();
            copy = false;
        } finally {
            try {
                fi.close();
                in.close();
                fo.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return copy;
    }

    /**
     * 文件复制
     *
     * @param srcFilePath
     * @param destDir
     * @return
     */
    public static boolean copyFile( String srcFilePath, String destDir ) {
        boolean     copy          = false;
        FileChannel inputChannel  = null;
        FileChannel outputChannel = null;
        try {
            createDir(destDir);
            File srcFile  = new File(srcFilePath);
            File destFile = new File(destDir + "/" + srcFile.getName());

            inputChannel = new FileInputStream(srcFile).getChannel();
            outputChannel = new FileOutputStream(destFile).getChannel();
            outputChannel.transferFrom(inputChannel, 0, inputChannel.size());

            copy = true;
        } catch (Exception e) {

        } finally {
            try {
                inputChannel.close();
            } catch (Exception e) {
            }
            try {
                outputChannel.close();
            } catch (Exception e) {
            }
        }
        return copy;
    }

    public static boolean isFileExists( Context context, String fileName ) {
        File file = new File(getAppPath(), fileName);
        return file.exists();
    }

    public static boolean isFileExists( String filePath, String fileName ) {
        File file = new File(filePath, fileName);
        return file.exists();
    }

    public static boolean isFileExists( String filePath ) {
        File file = new File(filePath);
        return file.exists();
    }

    public static boolean createDir( String dir ) {

        if (!isFileExists(dir)) {
            return new File(dir).mkdirs();
        }
        return true;
    }

    /**
     * 保存到sdcard
     *
     * @param b
     * @return
     */
    public static String savePic( Context context, Bitmap b, String sdDirPath ) {
        if (b == null || TextUtils.isEmpty(sdDirPath)) return "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.US);
        File file = new File(getAppPath(), sdDirPath);
        if (!file.exists()) {
            try {
                file.mkdirs();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String           fname   = file + "/" + sdf.format(new Date()) + "_screenshot.png";
        File             outFile = new File(fname);
        FileOutputStream fos     = null;
        try {

            fos = new FileOutputStream(outFile);
            if (null != fos) {
                boolean compress = b.compress(Bitmap.CompressFormat.PNG, 90, fos);
                if (compress) {
                    ToastUtil.getInstance((Activity) context).showLongToast("图片保存成功" + outFile.getAbsolutePath(), ToastUtil.TOAST_TYPE.SUCCESS);
                    //通知图库更新
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    intent.setData(Uri.fromFile(outFile));
                    context.sendBroadcast(intent);
                } else {
                    ToastUtil.getInstance((Activity) context).showToast("图片保存失败", ToastUtil.TOAST_TYPE.ERROR);
                }
                fos.flush();
                fos.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            ToastUtil.getInstance((Activity) context).showToast("图片保存失败", ToastUtil.TOAST_TYPE.ERROR);
        } catch (IOException e) {
            e.printStackTrace();
            ToastUtil.getInstance((Activity) context).showToast("图片保存失败", ToastUtil.TOAST_TYPE.ERROR);
        }
        return fname;
    }
}
